<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>心理健康自评量表</title>
  <style>
    /* 原有样式不变，此处省略（与之前代码一致） */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      user-select: none;
    }
    body {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #333;
      line-height: 1.6;
      font-size: 16px;
      -webkit-touch-callout: none;
      min-height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px;
    }
    .card {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      width: 100%;
      max-width: 900px;
      border-radius: 20px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      transition: all 0.3s ease;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    .progress-container {
      width: 100%;
      height: 6px;
      background-color: rgba(102, 126, 234, 0.2);
    }
    .progress-bar {
      height: 100%;
      background: linear-gradient(90deg, #667eea, #764ba2);
      width: 0%;
      transition: width 0.3s ease;
    }
    .content {
      padding: 25px 20px;
    }
    h1, h2, h3 {
      color: #2c3e50;
      margin-bottom: 20px;
      text-align: center;
      line-height: 1.4;
    }
    h1 {
      font-size: 24px;
      margin-top: 10px;
      background: linear-gradient(135deg, #667eea, #764ba2);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    h2 {
      font-size: 20px;
    }
    h3 {
      font-size: 18px;
      margin: 25px 0 20px;
      text-align: left;
      color: #34495e;
    }
    .intro-section {
      padding: 30px 25px;
      text-align: center;
      display: block;
    }
    .intro-content {
      margin-bottom: 25px;
    }
    .intro-text {
      margin-bottom: 20px;
      line-height: 1.7;
      text-align: left;
      font-size: 16px;
      color: #555;
    }
    .intro-list {
      text-align: left;
      margin: 20px 0 25px 25px;
      line-height: 1.7;
      font-size: 15px;
      color: #555;
    }
    .intro-list li {
      margin-bottom: 10px;
      padding-left: 10px;
    }
    .question-number {
      font-size: 16px;
      color: #666;
      margin-bottom: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
    }
    .question-text-container {
      min-height: 80px;
      margin-bottom: 25px;
    }
    .question-text {
      font-size: 18px;
      line-height: 1.7;
      color: #2c3e50;
      padding: 20px;
      background: rgba(102, 126, 234, 0.05);
      border-radius: 12px;
      border-left: 4px solid #667eea;
    }
    .options {
      display: flex;
      flex-direction: column;
      gap: 12px;
      margin-bottom: 30px;
    }
    .option {
      padding: 16px 20px;
      border-radius: 12px;
      background: white;
      border: 2px solid #e9ecef;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      font-size: 16px;
    }
    .option:hover {
      border-color: #667eea;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
    }
    .option.active {
      background: linear-gradient(135deg, #667eea, #764ba2);
      border-color: #667eea;
      color: white;
      font-weight: 500;
    }
    .option-letter {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: rgba(102, 126, 234, 0.1);
      color: #667eea;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      flex-shrink: 0;
      font-weight: 600;
      transition: all 0.3s ease;
    }
    .option.active .option-letter {
      background: rgba(255, 255, 255, 0.2);
      color: white;
    }
    .button-group {
      display: flex;
      justify-content: space-between;
      margin-top: 20px;
      gap: 15px;
    }
    .btn {
      padding: 14px 0;
      border-radius: 12px;
      border: none;
      cursor: pointer;
      font-weight: 600;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      flex: 1;
      font-size: 16px;
    }
    .btn-prev {
      background: rgba(102, 126, 234, 0.1);
      color: #667eea;
    }
    .btn-prev:hover {
      background: rgba(102, 126, 234, 0.2);
    }
    .btn-next {
      background: linear-gradient(135deg, #667eea, #764ba2);
      color: white;
      display: none;
    }
    .btn-next:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }
    .btn-start, .btn-restart {
      background: linear-gradient(135deg, #667eea, #764ba2);
      color: white;
      margin: 20px auto;
      display: block;
      padding: 16px 32px;
      font-size: 18px;
      width: 100%;
      max-width: 300px;
      border-radius: 12px;
    }
    .btn-start:hover, .btn-restart:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
    }
    .result-section {
      display: none;
    }
    .result-card {
      padding: 30px 25px;
    }
    .total-score {
      text-align: center;
      margin: 25px 0;
      padding: 25px;
      background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
      border-radius: 15px;
      border: 1px solid rgba(102, 126, 234, 0.1);
    }
    .total-score-value {
      font-size: 32px;
      font-weight: 700;
      background: linear-gradient(135deg, #667eea, #764ba2);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 10px 0;
    }
    .table-container {
      width: 100%;
      overflow-x: auto;
      margin: 20px 0 25px;
      border-radius: 12px;
      border: 1px solid rgba(102, 126, 234, 0.1);
    }
    .factors-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 15px;
    }
    .factors-table th,
    .factors-table td {
      padding: 12px 15px;
      text-align: center;
      border-bottom: 1px solid rgba(102, 126, 234, 0.1);
    }
    .factors-table th:first-child,
    .factors-table td:first-child {
      text-align: left;
    }
    .factors-table th {
      background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
      font-weight: 600;
      color: #2c3e50;
    }
    .factors-table tr:hover {
      background: rgba(102, 126, 234, 0.02);
    }
    .severity {
      padding: 6px 12px;
      border-radius: 20px;
      color: white;
      font-weight: 500;
      font-size: 12px;
      display: inline-block;
    }
    .severity-mild {
      background: linear-gradient(135deg, #48bb78, #38a169);
    }
    .severity-moderate-light {
      background: linear-gradient(135deg, #68d391, #48bb78);
    }
    .severity-moderate {
      background: linear-gradient(135deg, #ed8936, #dd6b20);
    }
    .severity-severe {
      background: linear-gradient(135deg, #f56565, #e53e3e);
    }
    .interpretation {
      background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
      padding: 25px;
      border-radius: 15px;
      margin: 25px 0;
      line-height: 1.7;
      font-size: 15px;
      border: 1px solid rgba(102, 126, 234, 0.1);
    }
    .factor-description {
      margin-top: 8px;
      font-size: 14px;
      color: #666;
      padding-left: 15px;
      border-left: 3px solid #667eea;
      line-height: 1.6;
    }
    .factor-description-container {
      margin: 15px 0;
      padding: 15px;
      background: white;
      border-radius: 12px;
      border: 1px solid rgba(102, 126, 234, 0.1);
    }
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }
    .question-container, .result-card, .intro-section, .expired-section {
      animation: fadeIn 0.5s ease forwards;
    }
    .hidden {
      display: none;
    }
    /* 过期提示样式 */
    .expired-section {
      padding: 50px 25px;
      text-align: center;
      display: none; /* 默认隐藏 */
    }
    .expired-title {
      font-size: 28px;
      color: #e53e3e;
      margin-bottom: 20px;
      font-weight: 700;
    }
    .expired-desc {
      font-size: 16px;
      color: #666;
      margin-bottom: 30px;
      line-height: 1.7;
    }
    .btn-shop {
      background: linear-gradient(135deg, #e53e3e, #c53030);
      color: white;
      padding: 16px 32px;
      font-size: 18px;
      border-radius: 12px;
      border: none;
      cursor: pointer;
      transition: all 0.3s ease;
    }
    .btn-shop:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(229, 62, 62, 0.3);
    }
    @media (max-width: 768px) {
      body { padding: 10px; }
      .content, .intro-section, .result-card, .expired-section { padding: 20px 15px; }
      .question-text { font-size: 17px; padding: 15px; }
      .option { padding: 14px 16px; }
      .factors-table { font-size: 14px; }
      .factors-table th, .factors-table td { padding: 10px 8px; }
      .expired-title { font-size: 24px; }
    }
    @media (max-width: 480px) {
      h1 { font-size: 22px; }
      .intro-text, .intro-list { font-size: 15px; }
      .button-group { flex-direction: column; }
      .factors-table th, .factors-table td { padding: 8px 6px; font-size: 13px; }
    }
  </style>
</head>
<body>
  <div class="page-container">
    <div class="card">
      <!-- 进度条 -->
      <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
      </div>

      <!-- 1. 过期提示页面（默认隐藏，验证失败时显示） -->
      <div class="expired-section" id="expiredSection">
        <div class="expired-title">链接过期</div>
        <div class="expired-desc">该链接已超过24小时有效期，请通过官方店铺获取最新链接</div>
        <!-- 跳转小红书首页（替换为你的小红书链接） -->
        <button class="btn-shop" id="shopBtn">官方店铺</button>
      </div>

      <!-- 2. 量表介绍页面（默认显示，验证通过时保留） -->
      <div class="intro-section" id="introSection">
        <h1>心理健康自评量表</h1>
        <div class="intro-content">
          <p class="intro-text">本量表包含90个项目，涵盖感觉、情感、思维、意识、行为、生活习惯、人际关系、饮食睡眠等多个方面，帮助您了解近期的心理状态。</p>
          <p class="intro-text">请注意：量表仅为辅助筛查工具，测试结果仅供参考，不能替代专业诊断。如果您有持续的心理困扰，建议寻求专业心理咨询。</p>
          <p class="intro-text">请仔细阅读每一条陈述，根据您最近一周内的实际感受，选择最符合的答案。</p>
          <ul class="intro-list">
            <li><strong>A、从无</strong>：没有或很少时间有</li>
            <li><strong>B、很轻</strong>：少部分时间有</li>
            <li><strong>C、中等</strong>：相当多时间有</li>
            <li><strong>D、偏重</strong>：绝大部分时间有</li>
            <li><strong>E、严重</strong>：全部时间都有</li>
          </ul>
        </div>
        <button class="btn btn-start" id="startBtn">开始测试</button>
      </div>

      <!-- 3. 题目容器（默认隐藏） -->
      <div class="content question-container hidden" id="questionContainer">
        <div class="question-number">
          <span>第 <span id="currentQuestionNum">1</span> 题</span>
          <span>共 90 题</span>
        </div>
        <div class="question-text-container">
          <div class="question-text" id="questionText"></div>
        </div>
        <div class="options" id="optionsContainer">
          <div class="option" data-point="1">
            <span class="option-letter">A</span>
            <span>从无</span>
          </div>
          <div class="option" data-point="2">
            <span class="option-letter">B</span>
            <span>很轻</span>
          </div>
          <div class="option" data-point="3">
            <span class="option-letter">C</span>
            <span>中等</span>
          </div>
          <div class="option" data-point="4">
            <span class="option-letter">D</span>
            <span>偏重</span>
          </div>
          <div class="option" data-point="5">
            <span class="option-letter">E</span>
            <span>严重</span>
          </div>
        </div>
        <div class="button-group">
          <button class="btn btn-prev" id="prevBtn">‹ 上一题</button>
          <button class="btn btn-next" id="nextBtn">下一题 ›</button>
        </div>
      </div>

      <!-- 4. 结果容器（默认隐藏） -->
      <div class="result-section" id="resultSection">
        <div class="result-card">
          <h2>测试结果分析</h2>
          <div class="total-score">
            <p>您的测试总分</p>
            <p class="total-score-value" id="totalScore">0</p>
            <p>单项平均分: <span id="averageScore">0.00</span></p>
          </div>
          <h3>各维度得分情况</h3>
          <div class="table-container">
            <table class="factors-table">
              <thead>
                <tr>
                  <th>维度名称</th>
                  <th>总分</th>
                  <th>平均分</th>
                  <th>程度</th>
                </tr>
              </thead>
              <tbody id="factorsTableBody"></tbody>
            </table>
          </div>
          <div id="factorDescriptions">
            <h3>维度说明</h3>
          </div>
          <div class="interpretation">
            <h3>结果说明</h3>
            <p>测试结果反映了您近期的心理状态，但请理解这只是一个参考指标。每个人的心理状态都会随着时间、环境和经历而变化。</p>
            <p>如果您在某些维度上得分较高，可能表明这些方面近期给您带来了一些困扰。建议您：</p>
            <ul style="margin: 15px 0 15px 25px;">
              <li>保持规律的作息和健康的饮食习惯</li>
              <li>寻找适合自己的放松方式</li>
              <li>与信任的亲友分享感受</li>
              <li>必要时寻求专业心理支持</li>
            </ul>
            <p>程度分级说明：</p>
            <ul style="margin: 10px 0 15px 20px;">
              <li><span class="severity severity-mild">有点</span>：症状轻微或偶尔出现</li>
              <li><span class="severity severity-moderate-light">轻微</span>：症状明显但不影响日常生活</li>
              <li><span class="severity severity-moderate">中度</span>：症状明显且对日常生活有一定影响</li>
              <li><span class="severity severity-severe">重度</span>：症状严重且明显影响日常生活</li>
            </ul>
          </div>
          <button class="btn btn-restart" id="restartBtn">重新测试</button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // ==============================================
    // 关键验证逻辑：链接创建时间校验 + 24小时过期判断
    // ==============================================
    const XHS_HOME_URL = "https://xhslink.com/m/7jnvxOqqrUv"; // 你的小红书首页链接
    const EXPIRY_HOURS = 24; // 过期时间：24小时

    // 1. 从URL参数中获取“链接创建时间戳”（格式：秒级，如1730000000）
    function getLinkCreateTime() {
      const params = new URLSearchParams(window.location.search);
      const createTimeStr = params.get("createTime"); // 读取?createTime=xxx参数
      return createTimeStr ? parseInt(createTimeStr) : null; // 转为数字，无则返回null
    }

    // 2. 验证链接是否有效（未过期 + 有时间戳）
    function isLinkValid() {
      const createTime = getLinkCreateTime();
      if (!createTime) return false; // 无时间戳 → 无效

      const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒级，与创建时间统一单位）
      const expireSeconds = EXPIRY_HOURS * 60 * 60; // 24小时转秒数
      return (now - createTime) <= expireSeconds; // 未超过24小时 → 有效
    }

    // 3. 验证结果处理：有效则显示量表，无效则显示过期提示
    function handleLinkValidation() {
      const isValid = isLinkValid();
      const expiredSection = document.getElementById("expiredSection");
      const introSection = document.getElementById("introSection");

      if (!isValid) {
        // 无效/过期：显示过期页面，隐藏量表
        expiredSection.style.display = "block";
        introSection.classList.add("hidden");
        document.getElementById("questionContainer").classList.add("hidden");
        document.getElementById("resultSection").style.display = "none";
      } else {
        // 有效：显示量表，隐藏过期页面
        expiredSection.style.display = "none";
        introSection.classList.remove("hidden");
      }
    }

    // ==============================================
    // 原有量表逻辑（题目、得分计算等，保持不变）
    // ==============================================
    // 90道测试题
    const questions = [
      "头痛", "神经过敏，心中不踏实", "头脑中有不必要的想法或字句盘旋", "头晕或晕倒", "对异性的兴趣减退",
      "对旁人责备求全", "感到别人能控制您的思想", "责怪别人制造麻烦", "忘性大", "担心自己的衣饰整齐及仪态的端正",
      "容易烦恼和激动", "胸痛", "害怕空旷的场所或街道", "感到自己的精力下降，活动减慢", "想结束自己的生命",
      "听到旁人听不到的声音", "发抖", "感到大多数人都不可信任", "胃口不好", "容易哭泣",
      "同异性相处时感到害羞不自在", "感到受骗，中了圈套或有人想抓住您", "无缘无故地突然感到害怕", "自己不能控制地大发脾气", "怕单独出门",
      "经常责怪自己", "腰痛", "感到难以完成任务", "感到孤独", "感到苦闷",
      "过分担忧", "对事物不感兴趣", "感到害怕", "您的感情容易受到伤害", "旁人能知道您的私下想法",
      "感到别人不理解您、不同情您", "感到人们对您不友好，不喜欢您", "做事必须做得很慢以保证做得正确", "心跳得很厉害", "恶心或胃部不舒服",
      "感到比不上他人", "肌肉酸痛", "感到有人在监视您、谈论您", "难以入睡", "做事必须反复检查",
      "难以做出决定", "怕乘电车、公共汽车、地铁或火车", "呼吸有困难", "一阵阵发冷或发热", "因为感到害怕而避开某些东西、场合或活动",
      "脑子变空了", "身体发麻或刺痛", "喉咙有梗塞感", "感到前途没有希望", "不能集中注意力",
      "感到身体的某一部分软弱无力", "感到紧张或容易紧张", "感到手或脚发重", "想到死亡的事", "吃得太多",
      "当别人看着您或谈论您时感到不自在", "有一些不属于您自己的想法", "有想打人或伤害他人的冲动", "醒得太早", "必须反复洗手、点数",
      "睡得不稳不深", "有想摔坏或破坏东西的想法", "有一些别人没有的想法", "感到对别人神经过敏", "在商店或电影院等人多的地方感到不自在",
      "感到任何事情都很困难", "一阵阵恐惧或惊恐", "感到公共场合吃东西很不舒服", "经常与人争论", "单独一人时神经很紧张",
      "别人对您的成绩没有做出恰当的评价", "即使和别人在一起也感到孤单", "感到坐立不安心神不定", "感到自己没有什么价值", "感到熟悉的东西变成陌生或不像是真的",
      "大叫或摔东西", "害怕会在公共场合晕倒", "感到别人想占您的便宜", "为一些有关性的想法而很苦恼", "您认为应该因为自己的过错而受到惩罚",
      "感到要很快把事情做完", "感到自己的身体有严重问题", "从未感到和其他人很亲近", "感到自己有罪", "感到自己的脑子有毛病"
    ];

    // 10个维度分组
    const factorGroups = [
      { name: '躯体化', indices: [0,3,11,26,39,41,47,48,51,52,55,57], description: '反映身体不适感，如头痛、肌肉酸痛等' },
      { name: '强迫症状', indices: [2,8,9,27,37,44,45,50,54,64], description: '反映无意义的思想、冲动和重复行为' },
      { name: '人际关系敏感', indices: [5,20,33,35,36,40,60,68,72], description: '反映人际交往中的不适感和自卑感' },
      { name: '抑郁症状', indices: [4,13,14,19,21,25,28,29,30,31,53,70,78], description: '反映抑郁情绪、兴趣减退和绝望感' },
      { name: '焦虑症状', indices: [1,16,22,32,38,56,71,77,79,85], description: '反映焦虑、紧张和恐慌感' },
      { name: '敌对症状', indices: [10,23,62,66,73,80], description: '反映敌对情绪和攻击倾向' },
      { name: '恐怖症状', indices: [12,24,46,49,69,74,81], description: '反映对特定场所、事物的恐惧' },
      { name: '偏执症状', indices: [7,17,42,67,75,82], description: '反映猜疑、关系妄想等症状' },
      { name: '精神病性', indices: [6,15,34,61,76,83,84,86,87,89], description: '反映精神病性症状表现' },
      { name: '睡眠饮食', indices: [18,43,58,59,63,65,88], description: '反映睡眠障碍和饮食异常' }
    ];

    // 应用状态
    let state = {
      currentQuestion: 0,
      answers: new Array(questions.length).fill(null),
      isTestCompleted: false
    };

    // DOM元素
    const elements = {
      // 过期相关
      shopBtn: document.getElementById("shopBtn"),
      // 量表相关
      currentQuestionNum: document.getElementById("currentQuestionNum"),
      questionText: document.getElementById("questionText"),
      optionsContainer: document.getElementById("optionsContainer"),
      progressBar: document.getElementById("progressBar"),
      prevBtn: document.getElementById("prevBtn"),
      nextBtn: document.getElementById("nextBtn"),
      startBtn: document.getElementById("startBtn"),
      restartBtn: document.getElementById("restartBtn"),
      totalScore: document.getElementById("totalScore"),
      averageScore: document.getElementById("averageScore"),
      factorsTableBody: document.getElementById("factorsTableBody"),
      factorDescriptions: document.getElementById("factorDescriptions"),
      questionContainer: document.getElementById("questionContainer"),
      resultSection: document.getElementById("resultSection"),
      introSection: document.getElementById("introSection")
    };

    // 初始化：先做链接验证，再绑定量表事件
    function init() {
      // 1. 优先处理链接验证
      handleLinkValidation();

      // 2. 绑定过期页面的跳转事件（小红书）
      elements.shopBtn.addEventListener("click", () => {
        window.open(XHS_HOME_URL, "_blank"); // 新窗口打开
      });

      // 3. 链接有效时，绑定量表事件
      if (isLinkValid()) {
        attachScaleEvents();
        loadProgress();
      }
    }

    // 绑定量表相关事件
    function attachScaleEvents() {
      // 开始测试
      elements.startBtn.addEventListener("click", () => {
        elements.introSection.classList.add("hidden");
        elements.questionContainer.classList.remove("hidden");
        showQuestion();
      });

      // 重新测试
      elements.restartBtn.addEventListener("click", restartTest);

      // 上一题/下一题
      elements.prevBtn.addEventListener("click", previousQuestion);
      elements.nextBtn.addEventListener("click", nextQuestion);

      // 选项点击
      elements.optionsContainer.querySelectorAll(".option").forEach(option => {
        option.addEventListener("click", () => selectOption(option));
      });

      // 键盘支持
      document.addEventListener("keydown", handleKeyPress);
    }

    // 加载未完成的测试进度
    function loadProgress() {
      const saved = localStorage.getItem("psychologicalTestProgress");
      if (saved) {
        state = JSON.parse(saved);
        if (state.isTestCompleted) showResults();
      }
    }

    // 保存测试进度
    function saveProgress() {
      localStorage.setItem("psychologicalTestProgress", JSON.stringify(state));
    }

    // 显示当前题目
    function showQuestion() {
      const qIndex = state.currentQuestion;
      elements.currentQuestionNum.textContent = qIndex + 1;
      elements.questionText.textContent = questions[qIndex];
      updateProgress();
      updateOptions();
      updateButtons();
    }

    // 更新进度条
    function updateProgress() {
      const progress = ((state.currentQuestion + 1) / questions.length) * 100;
      elements.progressBar.style.width = `${progress}%`;
    }

    // 更新选项状态（回显已选答案）
    function updateOptions() {
      const currentAnswer = state.answers[state.currentQuestion];
      elements.optionsContainer.querySelectorAll(".option").forEach(option => {
        option.classList.remove("active");
        if (parseInt(option.dataset.point) === currentAnswer) {
          option.classList.add("active");
        }
      });
    }

    // 更新按钮状态（上一题禁用/下一题显示）
    function updateButtons() {
      elements.prevBtn.disabled = state.currentQuestion === 0;
      elements.nextBtn.style.display = state.answers[state.currentQuestion] ? "flex" : "none";
    }

    // 选择选项
    function selectOption(option) {
      elements.optionsContainer.querySelectorAll(".option").forEach(opt => opt.classList.remove("active"));
      option.classList.add("active");
      state.answers[state.currentQuestion] = parseInt(option.dataset.point);
      updateButtons();
      saveProgress();

      // 自动跳转到下一题（最后一题则提交）
      setTimeout(() => {
        if (state.currentQuestion < questions.length - 1) {
          nextQuestion();
        } else {
          completeTest();
        }
      }, 300);
    }

    // 上一题
    function previousQuestion() {
      if (state.currentQuestion > 0) {
        state.currentQuestion--;
        showQuestion();
      }
    }

    // 下一题
    function nextQuestion() {
      if (state.currentQuestion < questions.length - 1) {
        state.currentQuestion++;
        showQuestion();
      }
    }

    // 键盘控制
    function handleKeyPress(e) {
      if (elements.questionContainer.classList.contains("hidden")) return;
      if (e.key >= 1 && e.key <= 5) {
        const option = elements.optionsContainer.querySelector(`.option[data-point="${e.key}"]`);
        if (option) selectOption(option);
      } else if (e.key === "ArrowLeft") previousQuestion();
      else if (e.key === "ArrowRight") nextQuestion();
    }

    // 完成测试
    function completeTest() {
      state.isTestCompleted = true;
      saveProgress();
      showResults();
    }

    // 显示结果
    function showResults() {
      elements.questionContainer.classList.add("hidden");
      elements.resultSection.style.display = "block";
      calculateResults();
    }

    // 计算得分
    function calculateResults() {
      // 总分
      const totalScore = state.answers.reduce((sum, ans) => sum + ans, 0);
      const avgScore = (totalScore / questions.length).toFixed(2);
      elements.totalScore.textContent = totalScore;
      elements.averageScore.textContent = avgScore;

      // 各维度得分
      elements.factorsTableBody.innerHTML = "";
      elements.factorDescriptions.innerHTML = "<h3>维度说明</h3>";
      factorGroups.forEach(factor => {
        // 维度总分和平均分
        const factorScore = factor.indices.reduce((sum, idx) => sum + state.answers[idx], 0);
        const factorAvg = (factorScore / factor.indices.length).toFixed(2);
        // 严重程度
        const severity = getSeverity(factorAvg);

        // 添加到表格
        const row = document.createElement("tr");
        row.innerHTML = `
          <td>${factor.name}</td>
          <td>${factorScore}</td>
          <td>${factorAvg}</td>
          <td><span class="severity ${severity.class}">${severity.level}</span></td>
        `;
        elements.factorsTableBody.appendChild(row);

        // 添加维度说明
        const descDiv = document.createElement("div");
        descDiv.className = "factor-description-container";
        descDiv.innerHTML = `
          <div style="display:flex;align-items:center;margin-bottom:8px;">
            <strong>${factor.name}</strong>
            <span class="severity ${severity.class}" style="margin-left:12px;">${severity.level}</span>
          </div>
          <p class="factor-description">${factor.description}</p>
        `;
        elements.factorDescriptions.appendChild(descDiv);
      });
    }

    // 获取严重程度
    function getSeverity(avg) {
      const numAvg = parseFloat(avg);
      if (numAvg < 2) return { level: "有点", class: "severity-mild" };
      if (numAvg < 3) return { level: "轻微", class: "severity-moderate-light" };
      if (numAvg < 4) return { level: "中度", class: "severity-moderate" };
      return { level: "重度", class: "severity-severe" };
    }

    // 重新测试
    function restartTest() {
      state = { currentQuestion: 0, answers: new Array(questions.length).fill(null), isTestCompleted: false };
      localStorage.removeItem("psychologicalTestProgress");
      elements.resultSection.style.display = "none";
      elements.introSection.classList.remove("hidden");
    }

    // 页面加载完成后初始化
    document.addEventListener("DOMContentLoaded", init);
  </script>
</body>
</html>